package controller;

import helper.AbstractAction;
import helper.ParseUtil;

import java.awt.Frame;
import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

import view.AnlegenKontoDialog;
import bank.Konto;
import bank.Kunde;


public class AnlegenKontoDialogController {

    private final BankHandler bankHandler;
    private final Frame parent;

    private AnlegenKontoDialog dialog;


    public AnlegenKontoDialogController(BankHandler aBankHandler, Frame aParent) {
        bankHandler = aBankHandler;
        parent = aParent;
    }

    public void start() {
        dialog = new AnlegenKontoDialog(parent, true);
        dialog.getBtAnlegen().addActionListener(new AnlegenKontoAction());
        dialog.getBtEnde().addActionListener(new BeendenAction());
    }

    private void clearDlgKontoAnlegen() {
        dialog.getTfName().setText("");
    }


    // Inner Classes ***********************************************************

    private class AnlegenKontoAction extends AbstractAction {
		@Override
		protected void execute(ActionEvent aEvent) throws Exception {
			int kundenNummer = ParseUtil.parseKundennummer(dialog.getTfName().getText());
            Kunde kunde = bankHandler.getKundeByKundenNummer(kundenNummer);

            String kontoArtString = dialog.getCbKontoArt().getSelectedItem().toString();
            int kontoArt = kontoArtString.equals("Girokonto") ? Konto.GIROKONTO
                                                              : Konto.SPARKONTO;

            Konto neuesKonto = kunde.anlegenKonto(kontoArt);
            JOptionPane.showMessageDialog(dialog, "Konto: " + neuesKonto.getKontonummer() + " angelegt.");
            clearDlgKontoAnlegen();
		}
    }

    private class BeendenAction extends AbstractAction {
		@Override
		protected void execute(ActionEvent aEvent) throws Exception {
            dialog.dispose();
		}
    }
}
